import { LIST_PAGE_PARAM_KEY, LIST_PAGESIZE_PARAM_KEY, LIST_SEARCH_PARAM_KEY } from '@/constant'
import { getQuestionList } from '@/service/module/question'
import { useRequest } from 'ahooks'
import { useSearchParams } from 'react-router-dom'

type optType = {
  isStar: boolean
  isDeleted: boolean
  pageSize: number
  page: number
}

const useQuestionListData = (opt: Partial<optType>) => {
  const { isDeleted, isStar } = opt
  const [searchParams] = useSearchParams()

  const { data, loading, error, refresh } = useRequest(
    async () => {
      const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
      const pageSize = parseInt(searchParams.get(LIST_PAGESIZE_PARAM_KEY) || '') || 10
      const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || '') || 1
      const data = await getQuestionList({ keyword, isStar, isDeleted, pageSize, page })
      return data
    },
    {
      refreshDeps: [searchParams], //刷新的依赖项  类似于useEffect里的依赖项
    }
  )

  return { data, loading, error, refresh }
}

export default useQuestionListData
